import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { memoApi } from "../backend/server";
import { MemoItem } from "../../views/Functions/children/Memo/Memo";
import { toast } from "../../components/Toast/Toast";

// export const deviceSlice = createSlice<typeof data,>(data)
const list: MemoItem[] = [];
const total: number = 0;
const pageSize: number = 10;
const pageNo: number = 1;

export const MemoSlice = createSlice({
  name: "memo",
  initialState: {
    list,
    total,
    pageSize,
    pageNo,
  },
  reducers: {},
  extraReducers: (builders) => {
    builders.addCase(fetchMemoList.fulfilled, (state, action) => {
      state.list = action.payload.list;
      state.total = action.payload.total || 0;
      state.pageNo = action.payload.pageNo || 1;
      state.pageSize = action.payload.pageSize || 10;
    });

    builders.addCase(fetchMemoList.rejected, (state, action) => {
      toast("fetch memo list error!");
      state.list = [];
    });
  },
});

export type FetchMemoType = {
  code: number;
  list: MemoItem[];
  pageNo: number;
  pageSize: number;
  total: number;
};

export const fetchMemoList = createAsyncThunk<
  FetchMemoType,
  Partial<{
    search: string;
    pageNo: number;
    pageSize: number;
  }>,
  {}
>("memo/fetchMemoList", async (params, action) => {
  return await memoApi.fetchMemoList(params);
});

export const memoReducer = MemoSlice.reducer;

export const {} = MemoSlice.actions;
